﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using System.Web;

namespace ltModel
{
    /// <summary>
    /// 新闻生成html
    /// </summary>
    public class BuilderNews
    {
        private static string templateFile = HttpContext.Current.Server.MapPath("~/html/template/template.html");//模板文件地址
        private static string newsFilePath = HttpContext.Current.Server.MapPath("~/html/");//生成的新闻存放目录
        private ltModel.Model.article_content nti = null;

        public BuilderNews(ltModel.Model.article_content Nti)
        {
            nti = Nti;
        }

        /// <summary>
        /// 把相应的关键字替换成具体内容
        /// </summary>
        private string Replacekeywords(string strTemplate)
        {
            strTemplate = strTemplate.Replace("$News_Title$", nti.Title);
            strTemplate = strTemplate.Replace("$News_Source$", nti.Source);
            strTemplate = strTemplate.Replace("$News_Author$", nti.author);
            strTemplate = strTemplate.Replace("$News_Content$", nti.Content);
            strTemplate = strTemplate.Replace("$News_Id$", nti.News_id.ToString());
            strTemplate = strTemplate.Replace("$News_Dat$", nti.Dat);
            return strTemplate;
        }

        public string Build(string newsFileName)
        {
            HtmlFileBuilder hfb = new HtmlFileBuilder(newsFileName, newsFilePath, templateFile, nti.News_id, Replacekeywords);
            return hfb.Build();
        }

        public static void ReBuildAll()
        {
            ltModel.BLL.article_content ac = new ltModel.BLL.article_content();
            DataTable dr = ac.GetAllList().Tables[0];
            for (int i = 0; i < dr.Rows.Count; i++)
            {
                System.Threading.Thread.Sleep(1);//暂停1毫秒
                string newsFileName = dr.Rows[i]["link"].ToString();//先从数据库中取文件名
                if (string.IsNullOrEmpty(newsFileName) || !newsFileName.EndsWith(".html"))//不存在则生成一个
                    newsFileName = DateTime.Now.ToString("yyyy/MM/dd/") + dr.Rows[i]["news_id"].ToString() + ".html";
                //判断数据库中是否已存在此文件名，取到不重复为止

                ltModel.Model.article_content news = ac.GetModel(Convert.ToInt32(dr.Rows[i]["news_id"]));
                string newFilename = new BuilderNews(news).Build(newsFileName);//生成
                ac.UpdateLink(Convert.ToInt32(dr.Rows[i]["news_id"]), newsFileName);//更新文件名
            }
        }

        public static void DeleteFile(string file)
        {
            string filepath = Path.Combine(newsFilePath, file);
            if (File.Exists(filepath))
                File.Delete(filepath);
        }
    }

    /// <summary>
    /// 替换模板内容
    /// </summary>
    /// <param name="TemplateContent">模板内容</param>
    /// <returns>被替换后的内容</returns>
    public delegate string ReplaceContent(string TemplateContent);

    public class HtmlFileBuilder
    {
        private string _htmlFilePath = string.Empty;//生成的html文件路径
        private string _templateFile = string.Empty;//模板文件
        private ReplaceContent _replaceMethod = null;//替换模板内容的方法
        private string _newHtmlFileName = string.Empty;//生成的html文件名称
        private int _id;
        static readonly List<string> DirectoryCache = new List<string>();//目录名称缓存

        public HtmlFileBuilder(string HtmlFilePath, string TemplateFile, int id, ReplaceContent ReplaceMethod)
        {
            _htmlFilePath = HtmlFilePath;
            _templateFile = TemplateFile;
            _replaceMethod = ReplaceMethod;
            _id = id;
        }

        public HtmlFileBuilder(string NewHtmlFileName, string HtmlFilePath, string TemplateFile, int id, ReplaceContent ReplaceMethod)
            : this(HtmlFilePath, TemplateFile, id, ReplaceMethod)
        {
            _newHtmlFileName = NewHtmlFileName;
        }
        
        /// <summary>
        /// 检查目录是否存在
        /// 不存在就创建，并把名称加入缓存
        /// </summary>
        /// <param name="absolutePath"></param>
        void CheckDirectoryExists(string absolutePath)
        {
            string absoluteFullPath = Path.GetDirectoryName(absolutePath);
            if (DirectoryCache.Contains(absoluteFullPath))
                return;

            if (!Directory.Exists(absoluteFullPath))
                Directory.CreateDirectory(absoluteFullPath);
            DirectoryCache.Add(absoluteFullPath);
        }

        public string Build()
        {
            Encoding code = Encoding.GetEncoding("gb2312");

            if (!File.Exists(_templateFile)) //判断文件是否存在
            {
                throw new Exception("模板文件：" + _templateFile + "不存在！");
            }

            string strTemplateContent = string.Empty;
            try
            {
                StreamReader sr = new StreamReader(_templateFile, code);
                strTemplateContent = sr.ReadToEnd(); //读取文件
                sr.Close();
            }
            catch (Exception exp)
            {
                HttpContext.Current.Response.Write(exp.Message);
                return string.Empty;
            }

            strTemplateContent = _replaceMethod(strTemplateContent);//写入具体内容

            if (string.IsNullOrEmpty(_newHtmlFileName) || !_newHtmlFileName.EndsWith(".html"))
                _newHtmlFileName = DateTime.Now.ToString("yyyy/MM/dd/") + _id.ToString() + ".html";
            try
            {
                CheckDirectoryExists(_htmlFilePath + _newHtmlFileName);
                StreamWriter sw = new StreamWriter(_htmlFilePath + _newHtmlFileName, false, code);
                sw.Write(strTemplateContent);
                sw.Flush();
                sw.Close();
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write(ex.Message);
                return string.Empty;
            }

            return _newHtmlFileName;//html文件名
        }
    }
}